//
//  LXChooseBrandViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/31.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXChooseBrandViewController.h"
#import "LXTopSearchView.h"
#import "PinPaiModel.h"
#import "SCIndexViewConfiguration.h"
#import "UITableView+SCIndexView.h"
@interface LXChooseBrandViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data,*letterData;
@property (nonatomic) NSMutableArray *brandAry,*hotsAry;
@property (nonatomic) LXChooseCarTypeViewController *carTypeVC;
@property(nonatomic) LXTopSearchView *searchView;

@end

@implementation LXChooseBrandViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self layoutCustomNav:self.view title:@"选择品牌"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    LXTopSearchView *searchView = [[LXTopSearchView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, kScreenWidth, 70)];
    [self.view addSubview:searchView];
    searchView.textField.placeholder = @"输入品牌名查询";
    [searchView setClickBtnBlock:^(NSString * _Nonnull text) {
        [self.view endEditing:YES];
        if (!StringIsEmpty(text)) {
            self.tableView.tableHeaderView = nil;
            NSMutableArray *searchAry = [NSMutableArray array];
            for (PinPaiModel *model in self.brandAry) {
                if ([model.label containsString:text]) {
                    [searchAry addObject:model];
                }
            }
            [self allocData:searchAry];
        }
        else {
            [self allocData:self.brandAry];
            self.tableView.tableHeaderView = [self setTableHeaderView];
        }
    }];
    self.searchView = searchView;
    
    
    [self.view addSubview:self.tableView];
    
    
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];

    [self.tableView.mj_header beginRefreshing];
   
    
    
    
}
-(CGFloat)height:(NSArray *)data{
    CGFloat height = data.count/3 * 35;
    if (data.count % 3!=0) {
        height = (data.count/3 + 1) * 35;
    }
    return height;
}
#pragma mark -- 热门车型
- (UIView *)setTableHeaderView{

        
    CGFloat head_H = [self height:self.hotsAry];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, head_H)];
    
    // 间距
    CGFloat margin = 20;
    CGFloat labelW = kScreenWidth/3 - 30;
    CGFloat labelH = 30;
    
   
    
    for (int i = 0; i < self.hotsAry.count; i++) {
       
        PinPaiChildrenModel *model = self.hotsAry[i];
        NSInteger row = i/3;
        NSInteger col = i%3;
        
        
        CGFloat labelX =  col  * (labelW + margin) + margin;
        CGFloat labelY =  row * (labelH + 5);
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(labelX, labelY, labelW, labelH)];
        label.backgroundColor = [UIColor colorWithRed:60/255.0 green:108/255.0 blue:252/255.0 alpha:0.1];
        label.text = model.label;
        label.textAlignment = NSTextAlignmentCenter;
        label.adjustsFontSizeToFitWidth = YES;
        label.textColor =  [UIColor colorWithHexString:@"#3C6CFC"];
        label.font = Fond15;
        label.layer.cornerRadius = 4;
        label.layer.masksToBounds = YES;
        [headView addSubview:label];
        
        
        [label whenTapped:^{
            if (self.ToSendValue) {
                self.ToSendValue(model);
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        
        
    }
    
    return headView;
}


- (void)loadData{
    
    //hot 热门品牌
    [MSNetworkManager postRevertUrl:TCarBrand_URL params:@{@"hot":@(1)} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        [self.tableView.mj_header endRefreshing];
        // 所有品牌列表
        self.brandAry = [PinPaiModel  mj_objectArrayWithKeyValuesArray:resonseObj[@"all"]];
        
        // 热门品牌
        if (!ObjectIsEmpty(resonseObj[@"list"])) {
            
            NSMutableArray *tempAry = [NSMutableArray array];
            for (NSDictionary *dic in resonseObj[@"list"]) {
                [tempAry addObjectsFromArray:dic[@"children"]];
            }
            self.hotsAry = [PinPaiChildrenModel  mj_objectArrayWithKeyValuesArray:tempAry];
            self.tableView.tableHeaderView = [self setTableHeaderView];
        }
    
        
        // 组装数据 按照首字母分组
        [self allocData:self.brandAry];
      
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self.tableView.mj_header endRefreshing];
    } withShowHud:YES];

    
}
#pragma mark -- 组装数据
-(void)allocData:(NSMutableArray *)brandAry{
    [self.data removeAllObjects];
    // 首字母数组
    self.letterData = [self pinyinAry:brandAry];
    for (int i = 0; i<self.letterData.count; i++) {
        NSString *letter = self.letterData[i];
        NSMutableArray *childrenAry = [NSMutableArray array];
        for (PinPaiModel *model in brandAry) {
            //获取当前文字的首字母
            NSString *firstLetter = [NSString getInitials:model.label];
            if ([letter isEqualToString:firstLetter]) {
                [childrenAry addObject:model];
            }
        }
        NSDictionary *dic = @{
            @"letter":letter,
            @"children":childrenAry
        };
        [self.data addObject:dic];
        
        
    }
    
    // 添加热门
    [self.letterData insertObject:@"热" atIndex:0];
    
    [self.tableView reloadData];
    
    self.tableView.sc_indexViewDataSource = self.letterData.mutableCopy;
    
}

#pragma mark --- 便利数组 获取首字符 去重
- (NSMutableArray *)pinyinAry:(NSArray *)ary{
    NSMutableArray *sectionAry = [NSMutableArray array];
    for (PinPaiModel *model in ary) {
        [sectionAry addObject:[NSString getInitials:model.label]];
    }
    NSSet *set = [NSSet setWithArray:sectionAry];
    NSMutableArray *letterAry = [NSMutableArray arrayWithArray:[set allObjects]];
    return letterAry;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dic = self.data[section];
    NSArray *children = dic[@"children"];
    return children.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([UITableViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = Color333;
        cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
        cell.detailTextLabel.textColor = [UIColor colorWithHexString:@"#AAAAAA"];
        [cell setClipsToBounds:YES];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }


    NSDictionary *dic = self.data[indexPath.section];
    NSArray *children = dic[@"children"];
    
    PinPaiModel *model = children[indexPath.row];
    cell.textLabel.text = model.label;
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *vv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth/2, 30)];
    vv.backgroundColor = UIColor.whiteColor;
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, kScreenWidth/2, 30)];
    lable.textColor = Color333;
    lable.font = Fond14;
    [vv addSubview:lable];

    NSDictionary *dic = self.data[section];
    lable.text = dic[@"letter"];
    return vv;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
    
}
//- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
//    return self.letterData;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.section];
    NSArray *children = dic[@"children"];

  

    PinPaiModel *model = children[indexPath.row];
    self.carTypeVC.data = model.children;
    [UIView animateWithDuration:0.01 animations:^{
        self.carTypeVC.view.X = 100;
    }];
    WEAKSELF
    [self.carTypeVC setToSendValue:^(PinPaiChildrenModel * _Nonnull model) {
        if (weakSelf.ToSendValue) {
            weakSelf.ToSendValue(model);
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];

   

}



- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}
- (NSMutableArray *)letterData{
    if (!_letterData) {
        _letterData = [[NSMutableArray alloc]init];
    }
    return _letterData;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, MaxY(self.searchView), ScreenWidth, kScreenHeight - MaxY(self.searchView)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = kComHeight;
        _tableView.contentInset = UIEdgeInsetsMake(0,0,kComHeight + 10,0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionIndexColor = Color999;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = YES;
        }
        SCIndexViewConfiguration *indexViewConfiguration = [SCIndexViewConfiguration configuration];
        indexViewConfiguration.indexItemSelectedBackgroundColor = mainColor;
        indexViewConfiguration.indexItemTextFont = Fond10;
        indexViewConfiguration.indexItemSelectedTextFont = Fond10;
        _tableView.sc_indexViewConfiguration = indexViewConfiguration;
        _tableView.sc_startSection = -1;
        _tableView.sc_indexViewDelegate = self;
 
    }
    return _tableView;
}
- (void)tableView:(UITableView *)tableView didSelectIndexViewAtSection:(NSUInteger)section{
    if (section==0) {
        [self.tableView setContentOffset:CGPointMake(0,0)animated:NO];
    }
    
}
- (LXChooseCarTypeViewController *)carTypeVC{
    if (!_carTypeVC) {
        
        
        UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
//        maskView.alpha = 0.5;
        [maskView whenTapped:^{
            [maskView removeFromSuperview];
            [self.carTypeVC.view removeFromSuperview];
            self.carTypeVC = nil;
            
//            [self layoutCustomNav:self.view title:@"选择品牌"];
            
        }];
        [self.view addSubview:maskView];
        
        
        _carTypeVC = [[LXChooseCarTypeViewController alloc] init];
        _carTypeVC.view.frame = CGRectMake(-kScreenWidth, 0, kScreenWidth-100, kScreenHeight);
        [_carTypeVC layoutCustomNav:self.view title:@"选择车型"];
        [self.view addSubview:_carTypeVC.view];
//        [self addChildViewController:_carTypeVC];
        
        
        
        
    }
    return _carTypeVC;
}

@end
@interface LXChooseCarTypeViewController()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;

@end
@implementation LXChooseCarTypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    
}


- (void)setData:(NSMutableArray *)data{
    
    _data = data;
    [self.tableView reloadData];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([UITableViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = Color333;
        [cell setClipsToBounds:YES];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    PinPaiChildrenModel *model = self.data[indexPath.row];
    cell.textLabel.text = model.label;
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *vv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth/2, 30)];
    vv.backgroundColor = ColorWithF5F5F5;
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, kScreenWidth/2, 30)];
    lable.textColor = Color333;
    lable.font = Fond14;
    [vv addSubview:lable];

    PinPaiChildrenModel *model = self.data[section];
    lable.text = [NSString stringWithFormat:@"品牌: %@",model.parent];
    return vv;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PinPaiChildrenModel *model = self.data[indexPath.row];
    if (self.ToSendValue) {
        self.ToSendValue(model);
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, ScreenWidth, kScreenHeight - LL_StatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = kComHeight;
        _tableView.contentInset = UIEdgeInsetsMake(0,0,kComHeight + 10,0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionIndexColor = Color999;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = YES;
        }
 
    }
    return _tableView;
}

@end
